(function() {

  var $editBanner = $(".edit_banner");
  var $deleteBanner = $(".delete_banner");
  //删除
  deleteBannerHandler();
  function deleteBannerHandler() {
    $deleteBanner.click(function() {
      var bannerId = $(this).attr('bannerId');
      layer.confirm('确认删除该轮播图吗？', {
        btn: ['确定', '取消'] //按钮
      }, function() {
        $.ajax({
          url: '/admin/banner/delete?bannerId=' + bannerId,
          dataType: 'json',
          success: function(data) {
            toastProp(data);
          },
          fail: function(err) {
            console.log(err);
          }
        });
      }, function() {})
    });
  }
  
  //新增与编辑
  addOrEdit();
  function addOrEdit() {
    var $name = $('#name');
    var $img = $('#img');
    var $href = $('#href');
    var $cancelEdit = $('#cancel_edit');
    var $submitAddOrEdit = $('#submitAddOrEdit');
    var isDisabled = $submitAddOrEdit.attr('disabled');//原先是否被禁用
    var params = {
      name: '',
      img: '',
      href: '',
    };
    //事件绑定
    //图片
    getInputDelayTrigger($img, function(data) {
      if (data) {
        $('#show_img').removeClass('hide').find('img').attr('src', data);
      } else {
        $('#show_img').addClass('hide').find('img').attr('src', '');
      }
    })
    //编辑按钮绑定
    $editBanner.click(function() {
      if ($(this).attr('editing')) {
        layer.msg('该轮播图正在编辑中~', {
          time: 1000
        });
        return;
      }
      var bannerId = $(this).attr('bannerId');
      var parent_id = $(this).attr('parent_id');
      var name = $(this).attr('name');
      var img = $(this).attr('img');
      var href = $(this).attr('link');
      $name.val(name);
      $img.val(img).trigger('input');
      $href.val(href);
      $cancelEdit.removeClass('hide')
      $editBanner.html('编辑').removeAttr('editing');
      $(this).attr('editing', 'editing').html('编辑中');
      $submitAddOrEdit.attr('bannerId', bannerId).html('更新').removeAttr('disabled');
    });

    //取消编辑
    $cancelEdit.click(function() {
      $name.val('');
      $img.val('').trigger('input');
      $href.val('');
      $cancelEdit.addClass('hide');
      $editBanner.html('编辑').removeAttr('editing');
      $submitAddOrEdit.removeAttr('bannerId').html('新增');
      if(isDisabled) $submitAddOrEdit.prop('disabled','disabled')
    });

    $submitAddOrEdit.click(function() {
      params.name = $name.val();
      params.img = $img.val();
      params.href = $href.val();
      params.id = $(this).attr('bannerId');
      $.ajax({
        url:'/admin/banner/addOrEdit',
        data: params,
        dataType: 'json',
        success: function(data){
          location.reload();
        }, 
        fail: function(err){
          layer.msg(err);
        }
      });

    });

  }


}())